<?php

namespace app\admin\controller\system;

use app\admin\model\SystemGroup;
use app\admin\model\SystemGroupAdmin;
use app\admin\validate\SystemAdmin;
use app\common\controller\AdminBase;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use util\Token;

/**
 * 系统管理员控制器
 */
class Admin extends AdminBase
{

    protected $model = null;

    protected $relationSearch = false;

    protected $prefix = "qu_";

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\SystemAdmin();
        $this->prefix = env('database.prefix');
    }


    /**
     * 下拉列表分页
     */
    public function selectPage()
    {

        try {
            list($limit, $where, $sortArr) = $this->buildTableParames();

            $page = $this->request->get('page', 1);
            // $limit = $this->request->get('limit', 100);
            $limit = 100;
            $show_id = $this->request->get('show_id', 'id'); //前端显示的value
            $query_field = $this->request->get('query_field', 'name'); //查询的参数名称
            $show_field = $this->request->get('show_field', 'name'); //前端显示的label
            $keyword = $this->request->get('keyword', ''); //查询的参数值

            $query_value = $this->request->get('query_value', ''); //编辑查询检索的值

            if ($query_value) {
                $where[] = [$show_id, '=', $query_value];
            }
            if ($keyword) {
                $where[] = [$query_field, 'LIKE', "%{$keyword}%"];
            }

            $fields = $show_id . ',' . $show_field;
            $count = $this->model
                ->where($where)
                ->count();
            $datalist = $this->model
                ->field($fields)
                ->where($where)
                ->page($page, $limit)
                ->select();
            $list = [];
            foreach ($datalist as $index => $item) {
                $result = [
                    $show_id => isset($item[$show_id]) ? $item[$show_id] : '',
                    $show_field => isset($item[$show_field]) ? $item[$show_field] : '',
                ];
                $list[] = $result;
            }
            $data = [
                'code' => 1,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        } catch (\Exception $e) {
            Log::error("--------:" . $e);
            return error("获取数据失败");
        }
    }

    /**
     * 列表
     */
    public function index()
    {

        $token = $this->request->header("token");

        list($limit, $where, $sortArr) = $this->buildTableParames();
        $is_superadmin = Token::is_superadmin($token);
        $admin_id = Token::userId($token);
        
        $where2 = array();
        foreach ($where as $k=>$v) {
            if($v[0] == 'group_id'){
                $where2['b.group_id'] = $v[2];
                unset($where[$k]);
                break;
            }
        }
        //查询group中id数据
        $system_info = table('system_group_admin')->where(['admin_id' => $admin_id])->find();
        if (!$is_superadmin && $system_info['group_id'] != 12) {
            $adminId = Token::userId($token);
            $where[] = ['id', '=', $adminId];
        }
        $list = $this->model
            ->alias('a')
            ->field('a.*,b.id as ids')
            ->join('qu_system_group_admin b', 'b.admin_id = a.id', 'left')
            ->where($where2)
            ->where($where)
            ->group('a.id')
            ->order('id desc')
            ->paginate($limit);
        $systemGroups = SystemGroup::where('status', 1)->column('id,name');
        $groupName = [];
        foreach ($systemGroups as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
        foreach ($list as $k => $v) {
            $group_arr = Db::table("{$this->prefix}system_group_admin")
                ->alias('sga')
                ->field('sg.name')
                ->leftJoin("{$this->prefix}system_group sg", 'sga.group_id=sg.id')
                ->where('sga.admin_id', $v['id'])
                ->select();

            $group_text = "";
            $i = 0;
            foreach ($group_arr as $key => $val) {
                $group_text = $i == 0 ? $val['name'] : $group_text . "," . $val['name'];
                $i++;
            }
            $v['group_text'] = $group_text;
            unset($v['password']);
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $list->items(),
        ];
        return json($data);
    }
    /**
     * 添加
     */
    public function add()
    {
        $token = $this->request->header("token");
        $adminId = Token::userId($token);
        $post = $this->request->post();
        Db::startTrans();
        try {
            validate(SystemAdmin::class)->check($post);
            $post['password'] = md5($post['password']);
            $post['admin_id'] = $adminId;
            $this->model->save($post);
            $row = $this->model->where('username', $post['username'])->find();
            // $group_ids=explode(',',$post['group_ids']);
            $group_ids = $post['group_ids'];
            $groupadmin = [];
            foreach ($group_ids as $v) {
                $groupadmin[] = ['admin_id' => $row['id'], 'group_id' => $v];
            }
            $groupadminModel = new SystemGroupAdmin();
            $groupadminModel->saveAll($groupadmin);
            Db::commit();
            return success('添加成功！');
        } catch (ValidateException $e) {
            return error($e->getError());
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("--------:" . $e);
            return error('添加失败:' . $e->getMessage());
        }
    }

    /**
     * 查找
     */
    public function find()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        $groups = SystemGroupAdmin::where('admin_id', $row['id'])->column('group_id');
        $row['group_ids'] = $groups;
        return success('ok', $row);
    }

    /**
     * 修改
     *
     */
    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }

        $post = $this->request->post();
        Db::startTrans();
        try {
            validate(SystemAdmin::class)->scene('edit')->check($post);
            if (isset($post['password']) && $post['password'] != "") {
                $post['password'] = md5($post['password']);
            } else {
                unset($post['password']);
            }
            $row->save($post);
            $groupadminModel = new SystemGroupAdmin();
            $groupadminModel->where('admin_id', $row['id'])->delete();
            //$group_ids=explode(',',$post['group_ids']);
            $group_ids = $post['group_ids'];
            $groupadmin = [];
            foreach ($group_ids as $v) {
                $groupadmin[] = ['admin_id' => $row['id'], 'group_id' => $v];
            }
            $groupadminModel->saveAll($groupadmin);
            Db::commit();
            return success('添加成功！');
        } catch (ValidateException $e) {
            return error($e->getError());
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("--------:" . $e);
            return error('保存失败');
        }

        return success('ok', $row);
    }

    /**
     * 数据删除
     */
    public function delete()
    {

        $id = input('id');
        $ids = is_array($id) ? $id : explode(',', $id);
        $row = $this->model->where("id", "in", $ids)->select();
        if ($row->isEmpty()) {
            return error('数据不存在');
        }
        if (in_array("1", $ids) || in_array(1, $ids)) {
            return error('当前管理员不可以删除!');
        }
        try {
            $save = $row->delete();
            SystemGroupAdmin::where('admin_id', 'in', $ids)->delete();
        } catch (\Exception $e) {
            return error('删除失败');
        }
        return $save ? success('删除成功！') : error('删除失败');
    }
}
